package weibo.web;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class SaveAndSubmit extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String cpt = req.getParameter("capId");
		String code = req.getParameter("code");
		String email = null;
		char[] c = code.toCharArray();
		//copy over the images and put it in the library
		for (int i = 0; i < c.length; i++) {
			File afile =new File(getServletContext().getRealPath("/")+"/"+(i+1)+".png");
			Date date = new Date();
			File bfile = new File("/Users/henrylian/Desktop/lab/letters/"+c[i]+"/"+date.getTime()+".png");
			FileUtils.copyFile(afile, bfile);
		}
		//grab the information from db and build up the form
		Connection connection = null;
		Statement stmt = null;
		try {
			Class.forName("org.h2.Driver");
			connection = DriverManager
					.getConnection("jdbc:h2:/Users/henrylian/Desktop/lab/db/h2/db","sa", "");
			stmt = connection.createStatement();
			ResultSet rs = stmt.executeQuery("select top(1) email from users where status = 0 order by id asc");
			while (rs.next()) {
	            email = rs.getString("EMAIL");
	        }
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 
//		HttpHost proxy = new HttpHost("connsvr.nike.com",8080);
		HttpClient httpClient = new DefaultHttpClient();
		
//		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
		
		HttpPost httpUriRequest = new HttpPost("http://3g.sina.com.cn/prog/wapsite/sso/register_submit.php?type=m&rand=950075907&backURL=http%3A%2F%2Fweibo.cn%2F&backTitle=%D0%C2%C0%CB%CE%A2%B2%A9&vt=4&revalid=2&ns=1");
		httpUriRequest.setHeader("Host","3g.sina.com.cn");
		httpUriRequest.setHeader("Origin","http://3g.sina.com.cn");
		httpUriRequest.setHeader("Connection","keep-alive");
		httpUriRequest.setHeader("Cache-Control","max-age=0");
		httpUriRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httpUriRequest.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
		httpUriRequest.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");	
		
		httpUriRequest.setHeader("Referer","http://3g.sina.com.cn/prog/wapsite/sso/register_submit.php?type=m&rand=950075907&backURL=http%3A%2F%2Fweibo.cn%2F&backTitle=%D0%C2%C0%CB%CE%A2%B2%A9&vt=4&revalid=2&ns=1");
		httpUriRequest.setHeader("Accept-Language","en-US,en;q=0.8");
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();

		nvps.add(new BasicNameValuePair("email", email));
		nvps.add(new BasicNameValuePair("pwd", "Nike1234"));
		nvps.add(new BasicNameValuePair("code", code));
		nvps.add(new BasicNameValuePair("backURL", "http://weibo.cn/"));
		String a = "新浪微博";
		String u8 = new String(a.getBytes("UTF-8"));
		nvps.add(new BasicNameValuePair("backTitle", u8));
		nvps.add(new BasicNameValuePair("type", "m"));
		nvps.add(new BasicNameValuePair("capId", cpt));
		nvps.add(new BasicNameValuePair("submit", "提交"));
		
		httpUriRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpUriRequest);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(httpResponse.getStatusLine().getStatusCode() == 200){
			//test
			HttpEntity entity = httpResponse.getEntity();
			String html = null;
			try {
				html = new String(EntityUtils.toString(entity).getBytes());
				
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        File file = new File("/Users/henrylian/Desktop/Test1.html");
	        FileWriter fwriter = new FileWriter(file);
	        fwriter.write(html);
	        fwriter.close();
			//update the status of the account in db
			try {
				stmt.execute("update USERS set status = 1 where email='"+email+"'");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//forward to /captcha with the message
			resp.sendRedirect("/captcha?booyah=yeah");
		}
		
		
		
	}

	
}
